package com.boarsoft.sofa.converter;

import java.util.Map;
import java.util.Map.Entry;

import com.alipay.hessian.generic.model.GenericMap;
import com.boarsoft.bean.ObjectConverter;
import com.boarsoft.rpc.generalize.RpcGenMap;

public class GenMapConverter implements ObjectConverter<GenericMap, RpcGenMap> {

	@SuppressWarnings("unchecked")
	public static RpcGenMap convert(GenericMap x) throws Exception {
		Map<Object, Object> sm = x.getMap();
		Map<Object, Object> tm = sm.getClass().newInstance();
		for (Entry<Object, Object> n: sm.entrySet()) {
			Object k = GenObjConverter.convert(n.getKey());
			Object v = GenObjConverter.convert(n.getValue());
			tm.put(k, v);
		}
		return new RpcGenMap(x.getType(), tm);
	}

	@SuppressWarnings("unchecked")
	public static GenericMap convert(RpcGenMap x) throws Exception {
		Map<Object, Object> sm = x.getMap();
		Map<Object, Object> tm = sm.getClass().newInstance();
		for (Entry<Object, Object> n: sm.entrySet()) {
			Object k = GenObjConverter.convert(n.getKey());
			Object v = GenObjConverter.convert(n.getValue());
			tm.put(k, v);
		}
		GenericMap gm = new GenericMap(x.getElClzName());
		gm.setMap(tm);
		return gm;
	}

	@Override
	public RpcGenMap convertAB(GenericMap a) throws Exception {
		return convert(a);
	}

	@Override
	public GenericMap convertBA(RpcGenMap b) throws Exception {
		return convert(b);
	}

}
